package cn.anc.aonicardv.net.download;

import android.content.Context;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import cn.anc.aonicardv.MyApplication;
import cn.anc.aonicardv.R;
import rx.Subscriber;

/**
 * Created by yangdai on 2017/6/7.
 */

public class DownLoadSubscriber<ResponseBody extends okhttp3.ResponseBody> extends Subscriber<ResponseBody> {
    private static String TAG = DownLoadSubscriber.class.getSimpleName();
    private DownLoadCallBack callBack;
    private Context context;
    private String path;
    private String name;

    public DownLoadSubscriber(String path, String name, DownLoadCallBack callBack, Context context) {
        this.path = path;
        this.name = name;
        this.callBack = callBack;
        this.context = context;
    }

    @Override
    public void onStart() {
        super.onStart();
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null)
                    callBack.onStart();

            }
        });

    }

    @Override
    public void onCompleted() {
    }


    @Override
    public void onError(final java.lang.Throwable e) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (callBack != null)
                    callBack.onError(e.getMessage());
            }
        });
    }


    final Handler handler = new Handler();

    @Override
    public void onNext(final ResponseBody responseBody) {

        if (Environment.getExternalStorageDirectory().getFreeSpace() < responseBody.contentLength())
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (callBack != null)
                        callBack.onError(MyApplication.getInstance().getString(R.string.recorder_album_not_enough_storage_available));
                    return;

                }
            });
        byte[] bytes = new byte[2048];
        try {
            InputStream inputStream = responseBody.byteStream();
            FileOutputStream fileOutputStream = new FileOutputStream(path + name);
            int length;
            int totelLength = 0;

            while ((length = inputStream.read(bytes, 0, bytes.length)) != -1) {
                totelLength = totelLength + length;
                fileOutputStream.write(bytes, 0, length);
                fileOutputStream.flush();
                final int finalTotelLength = totelLength;
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (callBack != null) {
                            callBack.onProgress(finalTotelLength, responseBody.contentLength());

                        }
                    }
                });
            }
            MediaScannerConnection.scanFile(context, new String[]{path + name}, null, new MediaScannerConnection.OnScanCompletedListener() {
                @Override
                public void onScanCompleted(final String path, final Uri uri) {
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (callBack != null)
                                callBack.onCompleted(path,uri);
                        }
                    });
                }
            });

            inputStream.close();
            fileOutputStream.close();

        } catch (Exception e) {
            new File(path+name).delete();
            e.printStackTrace();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    if (callBack != null)
                        callBack.onCancel();
                }
            });
        }


    }
}
